var gvkey = "";

var username = "";
var password = "";
var numberToRing = "";

var statusTimer = "";
var sdl = new Array();

var authenticated = false;


$(function() {
		
	System.Gadget.settingsUI = 'settings.html';

	System.Gadget.onSettingsClosed = settingsClosed;
	System.Gadget.onDock = checkState;
	System.Gadget.onUndock = checkState;
	loadSettings();
	renderSpeedDialList();
	checkState();
	
	$("#status").hide();	
	$("input#cancel").click(cancel);
	$("input#add").click(add);
	$("#addBox").keypress(keypress);
});


function saveSpeedDialList() {
	System.Gadget.Settings.write("sdl", $.toJSON(sdl));
}


function renderSpeedDialList() {	
	
	$("#speedDialList").empty();
		
	if (sdl.length > 0) {
		$("#emptyMessage").hide();
		
		for (i = 0; i < sdl.length; i++) {
			
			$("#speedDialList").append(createSpeedDialEntry(i, sdl[i].n, sdl[i].r));
		}
	
		$("a.sde").click(dial);
		$("a.deleteButton").click(deleteSpeedDial);
		$("a.moveUp").click(moveUp);

	} else {
		$("#emptyMessage").show();
	}
}


function loadSettings() {
	
	username = System.Gadget.Settings.readString("username");
	password = System.Gadget.Settings.readString("password");
	numberToRing = System.Gadget.Settings.readString("numberToRing");
	
	savedSDL = System.Gadget.Settings.readString("sdl");
	
	if (savedSDL.length > 0) {
		sdl = $.parseJSON(savedSDL, true);
	}	
}


function add(event) {
	
	sdl[sdl.length] = {
		n: $("#name").val(),
		r: $("#number").val()
	};
		
	saveSpeedDialList();
	renderSpeedDialList();
	resetAddBox();
}


function deleteSpeedDial(event) {

	var index = $(event.target).attr("name");	
	sdl.splice(index, 1);
	
	saveSpeedDialList();
	renderSpeedDialList();
}


function moveUp(event) {
	var index = $(event.target).attr("name");
	
	$(event.target).parent().before($(event.target).parent().prev().slice(0, 1));
	
}

function authenticate() {
	var galx = "";
	
	$.ajax({
		url: "https://www.google.com/voice",
		data: { },
		async: false,
		complete: function(xhr, status) {
			debugger;
			
			if (status == "success") {
				var cookie = xhr.getResponseHeader("Set-Cookie");
				var begin = cookie.indexOf("GALX=");
				var end = cookie.indexOf(";", begin + 1);
				galx = cookie.substring(begin + 5, end);
			}
		}
	});
	
	if (galx.length > 0)
	{
		debugger;
		var mydata = {
			ltmpl: "bluebar",			
			service: "grandcentral",
			GALX: galx,
			Email: username,
			Passwd: password,
			rmShown: "1",
			signIn: "Sign in",
			asts: ""
		};
			
		mydata["continue"] = "https://www.google.com/voice/account/signin/?prev=%2F";
		
		$.ajax({
			url: "https://www.google.com/accounts/ServiceLoginAuth?service=grandcentral",
			type: "POST",
			data: mydata,
			async: false,
			complete: function (xhr, status) {
				debugger;
				
				if (status == "success") {
					var text = xhr.responseText;
					var begin = text.indexOf("_rnr_se");
					begin = text.indexOf("value=", begin);
					var end = text.indexOf('"', begin + 7);
					
					gvkey = text.substring(begin + 7, end);
				}
			}
		});
		
		if (gvkey.length > 0) {
			authenticated = true;
		}
	}

}


function dial(event) {
		
	if (!authenticated) {
		authenticate();
		
		if (!authenticated) {
			return; //TODO: some sort of error message
		}
	}
			
	var params = {
		outgoingNumber: $(event.target).attr("title"),
		forwardingNumber: numberToRing,
		phoneType: 3,
		remember: 0,
		_rnr_se: gvkey 
	};

	$.post(
		"https://www.google.com/voice/call/connect",
		params,
		function() {			
			$("input#cancel").attr("name", params.number);
			$("#status").show(); 
			statusTimer = setTimeout("$('#status').hide()", 15000);
	});
		  	
	event.preventDefault();
}


function cancel(event) {

	clearTimeout(statusTimer);
	
	$.post("https://www.google.com/voice/m/callsms", 
		{ number: $(event.target).attr("name"),
		  cancel: "Cancel",
		  _rnr_se: gvkey },
		function() { 
			$("#status").hide(); 
		});	
}


function keypress(event) {

	if (event.which == 13)
	{
		$("input#add").click();
	}
}
	
function settingsClosed(event) {

    if (event.closeAction == event.Action.commit) {
		loadSettings();
	}
}


function createSpeedDialEntry(index, name, number) {
	
	var li = $('<li></li>');
	
	li.append($('<a class="sde" href="javascript:void;" title="' + number + '">' + name + '</a>'));
	//li.append($('<a class="moveUp" href="javascript:void;" name="' + index + '">up</a>'));
	li.append($('<a class="deleteButton" href="javascript:void;" name="' + index + '"></a>'));
	
	return li;
}


function checkState() { 

	if(!System.Gadget.docked) 
	{
		undockedState();
	} 
	else if (System.Gadget.docked)
	{
		dockedState(); 
	}
}

function resetAddBox() {
	
	$("#addBox input[type=text]").val("");
	$("input#name").focus();
}


function undockedState() { 

	with(document.body.style)
		width=260, 
		height=190;
		
	System.Gadget.background = 'img/bg_lg.png';	

	$("#addBox").show();
	$("a.deleteButton").show();
	
	resetAddBox();
}


function dockedState() {

	with(document.body.style)
		width=130, 
		height=190;
		
	System.Gadget.background = 'img/bg_sm.png';	
	
	$("#addBox").hide();
	$("a.deleteButton").hide();
}